import { memo, useEffect, useRef, useState } from 'react';
import {
  Form,
  Row,
  Col,
  Input,
  Button,
  Select,
  Textarea,
  MessagePlugin,
  Checkbox,
  Link,
  Space,
  DateRangePicker,
  Tag,
  Watermark,
} from 'tdesign-react';
import classnames from 'classnames';
import { SubmitContext, FormInstanceFunctions, FormRules, Data } from 'tdesign-react/es/form/type';
import CommonStyle from 'styles/common.module.less';
import Style from './index.module.less';
import dayjs, { Dayjs } from 'dayjs';
import store from '@/modules/store';
import { useLocation, useNavigate, Link as RouterLink } from 'react-router-dom';
import { getFloorListAPI, getRoomListByFloorIdAPI } from '@/api/floor.api'
import { approveReservationAPI, getReservationByIdAPI } from '@/api/reservation.api';
import { getStatusByDayAndRoomAPI, reserveRoomAPI } from '@/api/room.api'
import Notice from './Notice';
import { IFloor } from '@/pages/List/FloorManage/consts';
const { FormItem } = Form;
const { Option } = Select;

interface RoomState {
  floorNumber: number;
  roomNumber: string;
  roomId: string;
}
interface reverseData {
  roomId: string;
  startTime: string;
  endTime: string;
  purpose: string;
}
export default memo(() => {
  const location = useLocation();
  const floorAndRoomState = location.state as RoomState;
  // 预约提交的信息
  const [reverseData, setReverseData] = useState<reverseData>({
    roomId: '',
    startTime: '',
    endTime: '',
    purpose: '',
  });
  // 获取楼层信息
  const [floorList, setFloorList] = useState<IFloor[]>([]);
  // 获取search参数中的id
  const searchParams = new URLSearchParams(location.search);
  const reservationId = searchParams.get('id');
  const [reservation, setReservation] = useState<any>(null);
  useEffect(() => {
    getFloorListAPI().then(res => {
      if (res.status === 200) {
        const floors = res.data.data as IFloor[];
        setFloorList(floors);
      }
    });
  }, []);

  useEffect(() => {
    if (reservationId) {
      getReservationByIdAPI(reservationId).then(res => {
        setReservation(res.data.data);
      });
    }
  }, [reservationId]);
  // 获取路径
  const path = window.location.pathname;
  const navigate = useNavigate();
  const pathArr = path.split('/');
  const pathName = pathArr[pathArr.length - 1];
  const userData = store.getState().user.data;
  const { name: userName, studentId, gender, phone, email, role, department: { name: departmentName } } = userData;
  // 是否审批
  let isApprove = false;
  if (pathName === 'approve') isApprove = true;
  if (pathName === 'reverse') isApprove = false;
  // 表单实例
  const formRef = useRef<FormInstanceFunctions>();
  // 同意协议
  const [checkboxState, setCheckboxState] = useState<boolean>(false);
  // 包间状态
  enum RoomStatus {
    AVAILABLE = "available",
    OCCUPIED = "occupied",
    MAINTENANCE = "maintenance"
  }
  // 包间状态
  const [roomStatus, setRoomStatus] = useState<RoomStatus>(RoomStatus.AVAILABLE);
  // 同意协议
  const handleCheckboxChange = (checked: boolean) => {
    setCheckboxState(checked);
    formRef.current?.setFieldsValue?.({ agree: checked });
  };
  // 提交
  const onSubmit = (e: SubmitContext) => {
    if (e.validateResult === true) {
      reserveRoomAPI(reverseData).then((res) => {
        if (res.status === 200) {
          MessagePlugin.success("预约成功");
          navigate('/result/success');
        } else {
          MessagePlugin.error(res.data.message);
        }
      }).catch((err) => {
        if (err.response.status === 400) {
          MessagePlugin.error(err.response.data.message);
        } else {
          MessagePlugin.error(err.response.data.message);
        }
      });
    }
  };
  const rules: FormRules<Data> = {
    floor: [
      { required: true, message: "请选择楼层" }
    ],
    roomNumber: [
      { required: true, message: "请选择包间" }
    ],
    reason: [
      { required: true, message: "请输入申请事由" }
    ],
    agree: [
      { required: true, message: "请同意预约须知" },
      {
        validator: (val) => {
          return val
        }, message: "请同意预约须知"
      }
    ],
  }

  // 可选楼层 
  const [selectedFloor, setSelectedFloor] = useState<string>('');
  // 可选包间
  const [availableRooms, setAvailableRooms] = useState<{ id: string, status: RoomStatus, roomNumber: string }[]>([]);
  // 处理楼层改变
  const handleFloorChange = (value: any) => {
    const val = typeof value === 'string' ? value : String(value);
    setSelectedFloor(val);
    // 获取当前楼层的包间列表
    getRoomListByFloorIdAPI(Number(val)).then(res => {
      const rooms = (res.data.data.rooms || []).map((room: { id: string | number; status: string; roomNumber: string }) => ({
        id: String(room.id),
        status: room.status,
        roomNumber: room.roomNumber
      }));
      setAvailableRooms(rooms);
      // 清空包间
      formRef.current?.setFieldsValue?.({
        roomNumber: ''
      });
    });
  };
  // 处理包间变化
  const handleRoomChange = (value: any) => {
    const val = typeof value === 'string' ? value : String(value);
    setReverseData({
      ...reverseData,
      roomId: val,
    });
  };
  // 处理起止日期变化，自动计算天数
  const handleDateChange = (value: any, context: any) => {
    const dayjsValue = context.dayjsValue as Dayjs[];
    if (dayjsValue && dayjsValue[0] && dayjsValue[1]) {
      const days = dayjsValue[1].diff(dayjsValue[0], 'day') + 1;
      formRef.current?.setFieldsValue?.({ duration: days > 0 ? days : '' });
    } else {
      formRef.current?.setFieldsValue?.({ duration: '' });
    }
    setReverseData({
      ...reverseData,
      startTime: dayjsValue[0].format('YYYY-MM-DD'),
      endTime: dayjsValue[1].format('YYYY-MM-DD'),
    });
  };
  const initFormData = {
    username: userName,
    gender: gender === "male" ? '男' : gender === "female" ? "女" : "其他",
    departmentName: departmentName,
    role: role === "admin" ? "管理员" : role === "student" ? "研究生" : "教师",
    email: email,
    phone: phone,
    floor: selectedFloor,
  }

  useEffect(() => {
    // 只有审批页面且 reservation 和 楼层列表都已加载时执行
    if (isApprove && reservation && floorList.length > 0) {
      // 1. 找到楼层对象
      const floorObj = floorList.find(f => String(f.id) === String(reservation.room.floorId));
      if (floorObj) {
        setSelectedFloor(String(floorObj.id));
        // 2. 拉取该楼层的包间列表
        getRoomListByFloorIdAPI(floorObj.id).then(roomRes => {
          const rooms = (roomRes.data.data.rooms || []).map((room: { id: string | number; status: string; roomNumber: string }) => ({
            id: String(room.id),
            status: room.status,
            roomNumber: room.roomNumber
          }));
          setAvailableRooms(rooms);
          // 3. 设置包间状态
          const selectedRoom = rooms.find((room: { id: string; }) => room.id === String(reservation.roomId));
          if (selectedRoom) {
            setRoomStatus(selectedRoom.status);
          }
          // 4. 设置表单初始值
          formRef.current?.setFieldsValue?.({
            username: reservation.user?.name || reservation.userName,
            gender: reservation.user?.gender === "male" ? '男' : reservation.user?.gender === "female" ? "女" : "其他",
            departmentName: reservation.user?.department?.name || reservation.departmentName,
            role: reservation.user?.role === "admin" ? "管理员" : reservation.user?.role === "student" ? "研究生" : "教师",
            email: reservation.user?.email || reservation.email,
            phone: reservation.user?.phone || reservation.phone,
            floor: String(floorObj.id),
            roomNumber: String(reservation.roomId),
            startDate: [dayjs(reservation.startTime), dayjs(reservation.endTime)],
            duration: reservation.duration,
            reason: reservation.purpose,
          });
        });
      }
    }
  }, [isApprove, reservation, floorList]);

  useEffect(() => {
    // 仅普通预约页面，且 state 带有楼层和包间信息时自动回显
    if (!isApprove && floorList.length > 0 && floorAndRoomState && floorAndRoomState.floorNumber && floorAndRoomState.roomId) {
      // 找到对应楼层的 id
      const floorObj = floorList.find(f => String(f.floorNumber) === String(floorAndRoomState.floorNumber));
      if (floorObj) {
        setSelectedFloor(String(floorObj.id));
        // 获取该楼层的包间列表并设置包间
        getRoomListByFloorIdAPI(floorObj.id).then(res => {
          const rooms = (res.data.data.rooms || []).map((room: { id: string | number; status: string; roomNumber: string }) => ({
            id: String(room.id),
            status: room.status,
            roomNumber: room.roomNumber
          }));
          setAvailableRooms(rooms);
          // 设置包间状态
          const selectedRoom = rooms.find((room: { id: string }) => room.id === String(floorAndRoomState.roomId));
          if (selectedRoom) {
            setRoomStatus(selectedRoom.status);
          }
          // 设置表单初始值
          formRef.current?.setFieldsValue?.({
            floor: String(floorObj.id),
            roomNumber: String(floorAndRoomState.roomId)
          });
        });
      }
    }
  }, [isApprove, floorList, floorAndRoomState]);

  useEffect(() => {
    if (reverseData.roomId) {
      getStatusByDayAndRoomAPI(reverseData.startTime, reverseData.endTime, reverseData.roomId).then(res => {
        setRoomStatus(res.data.status);
      });
    }
  }, [reverseData.roomId, reverseData.startTime, reverseData.endTime]);
  function handleApprove() {
    if (reservationId) {
      approveReservationAPI(reservationId, 'approved').then(res => {
        if (res.data.status === 200) {
          MessagePlugin.success(res.data.message);
          navigate('/result/success');
        } else {
          MessagePlugin.error('同意审批失败');
        }
      });
    }
  }

  function handleReject() {
    if (reservationId) {
      approveReservationAPI(reservationId, 'rejected').then(res => {
        if (res.data.status === 200) {
          MessagePlugin.success(res.data.message);
          navigate('/room/approveList')
        } else {
          MessagePlugin.error('拒绝审批失败');
        }
      });
    }
  }

  // 取水印信息：优先用回显数据，否则用当前登录用户
  let watermarkStudentId = studentId;
  let watermarkUserName = userName;
  if (isApprove && reservation) {
    watermarkStudentId = reservation.studentId || reservation.user?.studentId || studentId;
    watermarkUserName = reservation.user?.name || reservation.userName || userName;
  }
  if (!isApprove && reservation) {
    watermarkStudentId = reservation.studentId || studentId;
    watermarkUserName = reservation.user?.name || reservation.userName || userName;
  }

  // 动态水印颜色
  const [watermarkColor, setWatermarkColor] = useState('#dcdcdc');
  useEffect(() => {
    // 获取当前主题对应的水印颜色
    const getWatermarkColor = () => {
      const themeMode = document.documentElement.getAttribute('theme-mode');
      return themeMode === 'dark' ? 'rgba(255,255,255,0.12)' : '#dcdcdc';
    };
    setWatermarkColor(getWatermarkColor());
    // 监听 theme-mode 属性变化
    const observer = new MutationObserver(() => {
      setWatermarkColor(getWatermarkColor());
    });
    observer.observe(document.documentElement, { attributes: true, attributeFilter: ['theme-mode'] });
    return () => observer.disconnect();
  }, []);

  return (
    <Watermark
      watermarkContent={{
        text: watermarkStudentId + ' ' + watermarkUserName,
        fontColor: watermarkColor,
      }}
      width={160}
      height={95.5}
      x={100}
      y={100}
      rotate={60}
    >
      <div className={classnames(CommonStyle.pageWithColor)}>
        <div className={Style.formContainer}>
          <Form ref={formRef} onSubmit={onSubmit} labelWidth={100} labelAlign='top' rules={rules} initialData={{ ...initFormData, agree: false }} style={{ zIndex: 100 }}>
            <div className={Style.titleBox}>
              <div className={Style.titleText}>{isApprove ? "审批信息" : "预约信息"}</div>
            </div>
            <Row gutter={[32, 24]}>
              <Col span={6}>
                <FormItem label='姓名' name='username'>
                  <Input disabled />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label='性别' name='gender'>
                  <Input disabled />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label='所属单位' name='departmentName' >
                  <Input disabled />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label='身份' name='role' >
                  <Input disabled />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label='Email' name='email' >
                  <Input disabled />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label='手机号' name='phone' >
                  <Input disabled />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label='起止日期' name='startDate'>
                  <DateRangePicker
                    mode='date'
                    format='YYYY-MM-DD'
                    enableTimePicker={false}
                    timePickerProps={{
                      steps: [1, 30, 0],
                      disableTime: (date) => {
                        // 限制小时为8-22点
                        const disabledHours = Array.from({ length: 24 }, (_, i) => i).filter(h => h < 8 || h > 22);
                        // 获取当前选择的小时
                        const hour = date;
                        // 如果是22点，禁用所有非00分钟  
                        if (hour === 22) {
                          return {
                            hour: disabledHours,
                            minute: Array.from({ length: 60 }, (_, i) => i).filter(m => m !== 0)
                          };
                        }
                        // 其他时间（8-21点）只允许00和30分钟
                        else {
                          return {
                            hour: disabledHours,
                            minute: Array.from({ length: 60 }, (_, i) => i).filter(m => m !== 0 && m !== 30)
                          };
                        }
                      },
                    }}
                    disabled={isApprove}
                    onChange={handleDateChange}
                    disableDate={{
                      before: dayjs().add(1, 'day').format('YYYY-MM-DD'),
                      after: dayjs().add(7, 'day').format('YYYY-MM-DD'),
                    }}
                  />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label='共计天数' name='duration'>
                  <Input placeholder='' disabled />
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label='楼层' name='floor'>
                  <Select placeholder='请选择楼层' disabled={isApprove} onChange={handleFloorChange}>
                    {floorList.map(floor => (
                      <Option key={floor.id} value={floor.id}>{floor.floorNumber}层</Option>
                    ))}
                  </Select>
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label={<Space>
                  包间
                  {roomStatus === RoomStatus.AVAILABLE && (
                    <Tag theme='success' variant='light'>可用</Tag>
                  )}
                  {roomStatus === RoomStatus.OCCUPIED && (
                    <Tag theme='danger' variant='light'>已占用</Tag>
                  )}
                  {roomStatus === RoomStatus.MAINTENANCE && (
                    <Tag theme='warning' variant='light'>维护中</Tag>
                  )}
                </Space>} name='roomNumber'>
                  <Select placeholder='请选择包间' disabled={isApprove || !selectedFloor} onChange={handleRoomChange}>
                    {availableRooms.map(room => (
                      <Option key={room.id} value={room.id}>{room.roomNumber}</Option>
                    ))}
                  </Select>
                </FormItem>
              </Col>

              <Col span={12}>
                <FormItem label='申请事由' name='reason'>
                  <Textarea disabled={isApprove} onChange={(e) => setReverseData({ ...reverseData, purpose: e })} />
                </FormItem>
              </Col>
              {isApprove ? <></> : <Col span={12}>
                <FormItem name='agree'>
                  <Checkbox value={checkboxState} onChange={handleCheckboxChange}>
                    <Link theme='primary' href="/form/userreverse/notice">
                      河南科技学院图书馆研究包间预约须知
                    </Link>
                  </Checkbox>
                </FormItem>
              </Col>}
            </Row>
            <FormItem style={{ marginTop: 30 }}>
              {isApprove ?
                <Space>
                  {reservation?.status !== 'approved' ?
                    <><Button type='button' theme='success' onClick={handleApprove} disabled={roomStatus !== RoomStatus.AVAILABLE}>
                      同意审批
                    </Button><Button type='button' theme='warning' onClick={handleReject}>
                        拒绝审批
                      </Button></>
                    :
                    <Button type='submit' theme='primary' disabled>
                      已审批
                    </Button>
                  }
                </Space>
                : <Button type='submit' theme='primary' disabled={roomStatus !== RoomStatus.AVAILABLE}>
                  提交
                </Button>
              }
            </FormItem>
          </Form>
        </div>
      </div>
    </Watermark>
  );
});
